package ui;
import java.lang.*;
import java.lang.reflect.InvocationTargetException;

import infrastructure.exceptions.PrivilidgesException;
import infrastructure.exceptions.ServerFataError;
import infrastructure.exceptions.operations.OperationException;
import inftrastructure.exceptions.ClientRuntimeException;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

import core.ServerFacade;
import core.conditions.PetsByTypeCondition;

import dal.IPet;
import dal.Pet;
import dal.Pet_type;
import dal.User;

import java.awt.*;              //for layout managers and more
import java.awt.event.*;        //for action events

import java.util.Iterator;
import java.util.Vector;

public class ClientFrame extends JFrame{
	
	// Data members definition
	final private int PET_NAME_COLUMN_NUM = 0;
	final private int PET_TYPE_COLUMN_NUM = 1;
	final private int SHORT_DESC_COLUMN_NUM = 2;
	final private int DELIVERED_BY_COLUMN_NUM = 3;
	final private int USER_ID_COLUMN_NUM = 4;
	final private int PET_ID_COLUMN_NUM = 5;

	protected User currUser = null;
	private ClientFrame clientframe = null;
	private PetDetailsFrame petDetailsFrame = new PetDetailsFrame(this);
	private AddPetDialog addPetDialog = null;
	private ManageUsersFrame manageUsersFrame = null;
	private ManagePetTypeFrame managePetTypeFrame = null;
	protected AnimalsAdoptionClient currClient = null;
	private int tableRowIndex;
	private Vector<IPet> petVec = null;
	private Iterator<IPet> petsIter = null;
	private Iterator<Pet_type> petsTypeIter = null;
	private Vector<Pet_type> petTypeVec = null;
	private String[] columnNames = {"Name", "Type", " Short Description", "delivered by"};

	
	// Components Definition
	private Container mainCotainer = null;
	private JPanel leftPane = null;
	private JPanel rightPane = null;
	private JPanel buttonsPanel = new JPanel(new GridBagLayout());
	private JPanel adminButtonsPanel = new JPanel(new GridBagLayout());
	private JPanel closeButtonPanel = new JPanel(new FlowLayout());
	protected JTable petsTable = null;
	private DefaultTableModel tableModel = null;
	private GridBagLayout gridbagLayout = new GridBagLayout();
    private GridBagConstraints gridbagConstrains = new GridBagConstraints();
    private JButton addpatButton = null;
    private JButton rempatButton = null;
    private JButton getPetDetailsButton = null;
    private JButton getAllPetsListButton = null;
    private JButton getPetsListByTypeButton = null;
    private JButton ManagePetTypesButton = null;
    private JButton closeButton = new JButton("Close");
    protected JButton ManageUsersButton = null;
    protected JComboBox petTypeComboBox = new JComboBox();
    
    // Create Event Handlers
    private addButtonHandler addbuttonHandler = new addButtonHandler();
    private remButtonHandler rembuttonHandler = new remButtonHandler();
    private getPetsListButtonHandler getpetsListButtonHandler = new getPetsListButtonHandler();
    private getPetDetailsButtonHandler getpetDetailsbuttonHandler = new getPetDetailsButtonHandler();
    private getPetsByTypeListButtonHandler getpetsByTypeListButtonHandler = new getPetsByTypeListButtonHandler();
    private manageUsersButtonHandler manageusersButtonHandler = new manageUsersButtonHandler();
    private managePetTypeButtonHandler managepetTypeButtonHandler = new managePetTypeButtonHandler();
    private closeButtonHandler closebuttonHandler = new closeButtonHandler();
    private tableHandler tablehandler = new tableHandler();
    
    // Constructor Definition
	public ClientFrame (AnimalsAdoptionClient client)
	{ 
		// set the title
		super("Pets Adoption Client");
		
		// Set reference to the main program
		currClient = client;
		
		// Set reference for this frame
		clientframe = this;

		// Get the user who logged in from the client
		currUser = client.facade.getLoggedInUser();

		// Get the main container of the JFrame
		mainCotainer = getContentPane();
		
		// Create the pans and set the layouts
		leftPane = new JPanel(new GridBagLayout());
		rightPane = new JPanel(new BorderLayout());
		
		// Create the Table Model
		 // The data is stored in an vector of vectors
		tableModel = new DefaultTableModel(columnNames, 15) 
		{
	        public boolean isCellEditable(int rowIndex, int mColIndex)
	        {
	        	// Disable user editing for all cells
	            return false;
	        }
	       public int getRowCount() 
	       {     	   
			   // Return the number element in the vector of vectors
			   return getDataVector().size();
	       }
	       public int getColumnCount() 
	       {
			   // Return the number of columns in the table
	    	    //(not equal to the num of columns in the data model
	    	   return columnNames.length;
	       }

		   public Object getValueAt(int row, int col)
		   {
			   // Get the value at - [row] is the index of the main vector
			    // [col] is the index of the item in the specific row vector
			   return (String)((Vector)getDataVector().elementAt(row)).elementAt(col);
		   }
		   public String getColumnName(int column)
		   {
			   return columnNames[column];
		   }
		   public Class getColumnClass(int col)
		   {
		       return getValueAt(0,col).getClass();
		   }
		   public void setValueAt(Object aValue, int row, int column) 
		   {
				// Check if the wanted row exists
				if (row >= getDataVector().size())
				{
					// We open a new row
					getDataVector().insertElementAt(new Vector<String>(), row);
				}
				// Insert cell data to the proper cell in the row 
			    ((Vector)getDataVector().elementAt(row)).insertElementAt(aValue, column);
		   }
		   public void insertRow (int row, Object[] rowData)
		   {
			   int index;
			   for (index = 0; index < rowData.length; index++)
			   {
				   // Insert the new row cell by cell
				   setValueAt(rowData[index], row, index);		  
			   }
		   }
	    }; // End of table model methods override
	    
	    // Create table with our custom data model
		petsTable = new JTable(tableModel);
		
		// Disable multi rows selection
		petsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		
		// Disable the ability to select a single cell (only row selection)
		petsTable.setColumnSelectionAllowed(false);
		petsTable.setRowSelectionAllowed(true);

		// Create User Action Buttons
		addpatButton = new JButton ("Add pet to repository");
		rempatButton = new JButton ("Remove pet from repository");
		getPetDetailsButton = new JButton ("Get pet's details");
		getAllPetsListButton = new JButton ("Get all pets list");
		getPetsListByTypeButton = new JButton ("Get pets by type list");
		JButton[] buttons = {addpatButton, rempatButton, getPetDetailsButton, getAllPetsListButton, getPetsListByTypeButton};

		// Set User Action buttons' tooltips
		addpatButton.setToolTipText("Give pet for adoption");
		rempatButton.setToolTipText("Remove pet that has been adopted from Repository.\n" +
				"Only pet's giver is allowed to remove it from repository");
		getPetDetailsButton.setToolTipText("Get selected pet's details");
		getAllPetsListButton.setToolTipText("Display all pets from repository");
		getPetsListByTypeButton.setToolTipText("Display pets by type from repository");
		
		// Create Admin Action Buttons
		ManageUsersButton = new JButton ("Manage Users");
		ManagePetTypesButton = new JButton ("Manage Pet Types");
		JButton[] adminButtons = {ManageUsersButton, ManagePetTypesButton};
		
		// Set Admin Action buttons' tooltips
		ManageUsersButton.setToolTipText("Add users to the system");
		ManagePetTypesButton.setToolTipText("Add pet type to the system");
	
		// Set ComboBox properties
		petTypeComboBox.setFont(new Font("DialogInput", Font.PLAIN, 12));
		petTypeComboBox.setEditable(false);
		
		// Link components to appropriate ActionListeners 
		addpatButton.addActionListener(addbuttonHandler);
		rempatButton.addActionListener(rembuttonHandler);
		getPetDetailsButton.addActionListener(getpetDetailsbuttonHandler);
		getAllPetsListButton.addActionListener(getpetsListButtonHandler);
		getPetsListByTypeButton.addActionListener(getpetsByTypeListButtonHandler);
		ManageUsersButton.addActionListener(manageusersButtonHandler);
		ManagePetTypesButton.addActionListener(managepetTypeButtonHandler);
		closeButton.addActionListener(closebuttonHandler);
		petsTable.addMouseListener(tablehandler);
		
		// Add components to container
		addButtonsRows(buttons, buttonsPanel);
		addAdminButtonsRows(adminButtons, adminButtonsPanel);
		
		buttonsPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("User Actions"),
                BorderFactory.createEmptyBorder(5,5,5,5)));
		
		adminButtonsPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("Administrator Actions"),
                BorderFactory.createEmptyBorder(5,5,5,5)));
		
		rightPane.add(new JScrollPane(petsTable),BorderLayout.CENTER);
		rightPane.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("Pets List"),
                BorderFactory.createEmptyBorder(5,5,5,5)));
		
		//leftPane.add(buttonsPanel,BorderLayout.NORTH);
		//leftPane.add(buttonsPanel);
		setButtonsPanel(leftPane);
	
		leftPane.setOpaque(true); 
		leftPane.setPreferredSize(new Dimension(210, 465));
		rightPane.setOpaque(true); 
		mainCotainer.add(leftPane, BorderLayout.LINE_START);
		mainCotainer.add(rightPane, BorderLayout.LINE_END);
		closeButtonPanel.add(closeButton);
		mainCotainer.add(closeButtonPanel, BorderLayout.SOUTH);
		
		// if user press on X button then close connection and exit
		addWindowListener(new WindowAdapter(){
			public void windowClosing (WindowEvent e){
				closebuttonHandler.actionPerformed(null);
			}
		});

		// Refresh the table
		getpetsListButtonHandler.actionPerformed(null);
		
		// Display the window
		setLocation(500, 500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		initPetTypeCombo();
		setResizable(false);
		pack();
		setLocationRelativeTo(null);
		setVisible(true);
	}
	
	// Methods Definition
	private void addButtonsRows(JButton[] buttons,
            Container container)
	{
		/** This method adds components to a container using GridBagLayout.
		 * Each type of component has a proper GridBagConstraints.*/
		
		int index;		
        int numofButtons = buttons.length;
		Insets buttonsInsets = new Insets(3,1,3,1);
		GridBagConstraints buttonsGridbagConstrains = new GridBagConstraints();
		GridBagConstraints comboBoxGridbagConstrains = new GridBagConstraints();

		buttonsGridbagConstrains.anchor = GridBagConstraints.CENTER; // Align to center of pane
		buttonsGridbagConstrains.gridx = 0; // Buttons at the first column
    	buttonsGridbagConstrains.fill = GridBagConstraints.HORIZONTAL;
    	buttonsGridbagConstrains.weightx = 1.0;
    	buttonsGridbagConstrains.gridwidth = 2; // each button occupies 2 cell
    	buttonsGridbagConstrains.insets = buttonsInsets;

        for (index = 0; index < (numofButtons - 1); index++)
        {
        	buttonsGridbagConstrains.gridy = index; // Each button in a different row
        	container.add(buttons[index], buttonsGridbagConstrains);
        }
        
        // Add get pets-by-list button and pet-type ComboBox
    	buttonsGridbagConstrains.gridy = index; 
    	buttonsGridbagConstrains.weightx = 0.5;
        buttonsGridbagConstrains.gridwidth = 1; // this button occupies 1 cell
        container.add(buttons[index], buttonsGridbagConstrains);
        
        comboBoxGridbagConstrains.gridy = index; // ComboBox is in the same row as the button
        comboBoxGridbagConstrains.gridx = 1; // ComboBox at right of the button
        comboBoxGridbagConstrains.anchor = GridBagConstraints.CENTER;
        comboBoxGridbagConstrains.fill = GridBagConstraints.HORIZONTAL;
        comboBoxGridbagConstrains.weightx = 0.5;
        comboBoxGridbagConstrains.gridwidth = 1; // ComboBox occupies 1 cell
        comboBoxGridbagConstrains.insets = buttonsInsets;
        container.add(petTypeComboBox, comboBoxGridbagConstrains);
	}
	
	private void addAdminButtonsRows(JButton[] buttons,
            Container container)
	{
		/** This method adds components to a container using GridBagLayout.
		 * Each type of component has a proper GridBagConstraints.*/
		
		int index;		
        int numofButtons = buttons.length;
		Insets buttonsInsets = new Insets(1,1,1,1);
		GridBagConstraints buttonsGridbagConstrains = new GridBagConstraints();

		buttonsGridbagConstrains.anchor = GridBagConstraints.NORTH;
		buttonsGridbagConstrains.gridx = 0; // Buttons at the first column
    	buttonsGridbagConstrains.fill = GridBagConstraints.HORIZONTAL;
    	buttonsGridbagConstrains.weightx = 1.0;
    	buttonsGridbagConstrains.weighty = 1.0;
    	buttonsGridbagConstrains.gridwidth = 1; // each button occupies 1 cell
    	buttonsGridbagConstrains.insets = buttonsInsets;

        for (index = 0; index < (numofButtons); index++)
        {
        	buttonsGridbagConstrains.gridy = index; // Each button in a different row
        	container.add(buttons[index], buttonsGridbagConstrains);
        }
	}
		
	private void setButtonsPanel(Container container)
	{
		int index;		
		Insets panelInsets = new Insets(1,1,1,1);
		GridBagConstraints userPanelsGridbagConstrains = new GridBagConstraints();
		GridBagConstraints adminPanelsGridbagConstrains = new GridBagConstraints();


		userPanelsGridbagConstrains.anchor = GridBagConstraints.CENTER;
		userPanelsGridbagConstrains.gridx = 0; // Users' buttons panel at the first column
		userPanelsGridbagConstrains.gridy = 0; // Users' buttons panel at the first row
		userPanelsGridbagConstrains.fill = GridBagConstraints.HORIZONTAL;
		userPanelsGridbagConstrains.weightx = 1.0;
		userPanelsGridbagConstrains.weighty = 1.0;
		userPanelsGridbagConstrains.gridwidth = 1; 
		userPanelsGridbagConstrains.gridheight = 5; // Panel occupies 5 cells - as the number of buttons in it
		userPanelsGridbagConstrains.insets = panelInsets;
    	
		adminPanelsGridbagConstrains.anchor = GridBagConstraints.NORTH;
		adminPanelsGridbagConstrains.gridx = 0; 
		adminPanelsGridbagConstrains.gridy = 5; // Admins' buttons panel at the sixth row
		adminPanelsGridbagConstrains.fill = GridBagConstraints.HORIZONTAL;
		adminPanelsGridbagConstrains.weightx = 1.0;
		adminPanelsGridbagConstrains.weighty = 1.0;
		adminPanelsGridbagConstrains.gridwidth = 1; 
		adminPanelsGridbagConstrains.gridheight = 2; // Panel occupies 2 cells - as the number of buttons in it
		adminPanelsGridbagConstrains.insets = panelInsets;

		container.add(buttonsPanel, userPanelsGridbagConstrains);
		// Add admin buttons to container only if the user is administrator
		if (currUser.isAdministrator())
		{
			container.add(adminButtonsPanel, adminPanelsGridbagConstrains);
		}
	}
	
	// Inner classes definition
	protected class tableHandler extends MouseAdapter {
		public void mouseClicked(MouseEvent e)
		{			
			// Get selected row
			tableRowIndex = petsTable.getSelectedRow();
			if (e.getClickCount() == 2)
			{		         
		         // Display pet's details when the user double click on pet's row
		         getpetDetailsbuttonHandler.actionPerformed(null);
			}
		}
	}
	
	protected class closeButtonHandler implements ActionListener {
		public void actionPerformed (ActionEvent e) 
		{
			// Close connection to server and exit
			try
			{
				currClient.facade.logout();
			}
			catch (ServerFataError ex)
			{
				// Server must be down
				System.exit(1);
			}
			catch (Exception ex)
			{
				System.exit(1);
			}
			//Perform normal exit
			System.exit(0);
		}
	}
	
    protected class addButtonHandler implements ActionListener {
		public void actionPerformed (ActionEvent e) 
		{			
				SwingUtilities.invokeLater(new Runnable() {
				    public void run()
				    {
						// Display AddPetDialog frame
				    	addPetDialog = new AddPetDialog(clientframe, "Add Pet Dialog");
						getpetsListButtonHandler.actionPerformed(null);
				    }
				});
		}
	}

	protected class remButtonHandler implements ActionListener {
		public void actionPerformed (ActionEvent e) 
		{
			/** This Class handle removing pets, by their owner, from the repository.
			 * First we check that the vector with pet objects is not corrupted.
			 * Then we check if the user is the owner of the pet by comparing his ID
			 * to the DeliveredBy ID of the selected pet. If OK we remove the pet from
			 * DB and refresh pets list */
						
			// Get selected table's row
			tableRowIndex = petsTable.getSelectedRow();
			
			if (tableRowIndex == -1)
			{
				// No row was selected - do nothing
				return;
			}
									
			// Check that pets vector is updated and synchronize with table
			if ((petVec.get(tableRowIndex).getId()) == (Integer.valueOf((String)((Vector)tableModel.getDataVector().elementAt(tableRowIndex)).elementAt(PET_ID_COLUMN_NUM))))
			{
				// Check if the user is the owner of the per 
				if (currUser.getId() == Integer.valueOf((String)((Vector)tableModel.getDataVector().elementAt(tableRowIndex)).elementAt(USER_ID_COLUMN_NUM)))
				{
					try
					{
						// Remove pet from DB
						currClient.session.removePetFromSystem(petVec.get(tableRowIndex).getId());
					}
					catch (OperationException ex)
					{
						JOptionPane.showMessageDialog(null, "Error deleting pet from repository",
								"Error", JOptionPane.ERROR_MESSAGE);
						return;
					}
					catch (PrivilidgesException ex)
					{
						JOptionPane.showMessageDialog(null, "Insufficient privileges to preform operation",
								"Error", JOptionPane.ERROR_MESSAGE);
						return;
					}
					catch(Exception ex)
					{
						// Unknown error
						throw new ClientRuntimeException(ex.getMessage(), ex);
					}
					
					// Refresh the table after removing pet
					getpetsListButtonHandler.actionPerformed(null);
				}
				else
				{
					// If the user is not who delivered the selected pet
					JOptionPane.showMessageDialog(null, "Only the user who delivered the pet is allow to remove it from the adoption list",
							"Error", JOptionPane.ERROR_MESSAGE);
				}
				
				// Force table update its view
				tableModel.fireTableDataChanged();
			}
			else
			{
				// Critical Error - If the pet's vector is not synch with table
				JOptionPane.showMessageDialog(null, "Fatal Error in pets table!!!",
						"Error", JOptionPane.ERROR_MESSAGE);
				System.exit(1);
			}
		}
	}
	
	protected class getPetsListButtonHandler implements ActionListener {
		public void actionPerformed (ActionEvent e) 
		{
			/** This Class updating pet's list that in the table view.
			 * We retrieve the entire pet's list in iterator and insert each
			 * pet's data into table. Because we save the data in the tableModel as Strings
			 * we save each pet object in a pets vector. We need the pets objects
			 * for other operations.  */
						
			// Variables Definition
			String petName = new String();
			String petTypeStr = new String();
			String shortDescStr = new String();
			String deliveredByStr = new String();
			String userID = new String();
			String petID = new String();

			int index = 0;
			
			// Clear current values in table
			tableModel.setRowCount(0);
			
			try
			{
				// get all-pets iterator from the client parent frame
				petsIter = currClient.session.getAllPets();
				if (petVec == null)
				{
					petVec = new Vector<IPet>();
				}
				else
				{
					// Clear old values
					petVec.removeAllElements();
				}
				
				// Updating table
				while (petsIter.hasNext())
				{
					// Get current pet from iterator
					petVec.add(petsIter.next());
					// Get pet's details
					petName = petVec.get(index).getName();
					petTypeStr = petVec.get(index).getPet_type().getType_name();
					shortDescStr = petVec.get(index).getShort_desc();
					deliveredByStr = petVec.get(index).getDeliver_user().getUsername();
					userID = Integer.toString(petVec.get(index).getDeliver_user().getId());
					petID = Integer.toString(petVec.get(index).getId());
					
					String [] data = {petName, petTypeStr, shortDescStr, deliveredByStr, userID, petID} ;
					try
					{
						// Insert current row data into table using table's data model
						tableModel.insertRow(index, data);
						index++;
					}
					catch(ArrayIndexOutOfBoundsException ex)
					{
						throw new ClientRuntimeException(ex.getMessage(), ex);
					}
				}				
			}
			catch (PrivilidgesException ex)
			{
				JOptionPane.showMessageDialog(null, "Insufficient privileges to preform operation",
						"Error", JOptionPane.ERROR_MESSAGE);
				return;
			}
			catch(Exception ex)
			{
				throw new ClientRuntimeException(ex.getMessage(), ex);
			}
			
			// Force table update its view
			tableModel.fireTableDataChanged();
		}
	}
	
	protected class getPetsByTypeListButtonHandler implements ActionListener {
		public void actionPerformed (ActionEvent e) 
		{
			/** This Class retrieve pets by type and update list in table view.
			 * We retrieve pet's by the type selected in ComboBox. We insert each
			 * pet's data into table. Because we save the data in the tableModel as Strings
			 * we save each pet object in a pets vector. We need the pets objects
			 * for other operations.  */
						
			// Variables Definition
			String petName = new String();
			String petTypeStr = new String();
			String shortDescStr = new String();
			String deliveredByStr = new String();
			String userID = new String();
			String petID = new String();

			int index = 0;
			
			try
			{
				// Get pets-by-type iterator from the client parent frame
				petsIter = currClient.session.getPets(new PetsByTypeCondition(petTypeVec.elementAt(petTypeComboBox.getSelectedIndex())));
								
				if (!petsIter.hasNext())
				{
					// If no rows where retrieved or if the PetType table is empty
						// - then do nothing and return
					JOptionPane.showMessageDialog(null, "No pets from type - " + petTypeComboBox.getSelectedItem() + " where found.",
							"No pet type found in repository", JOptionPane.INFORMATION_MESSAGE);
					return;
				}
				// Clear current values in table
				tableModel.setRowCount(0);
				
				if (petVec == null)
				{
					petVec = new Vector<IPet>();
				}
				else
				{
					// clear old values
					petVec.removeAllElements();
				}
				
				// Updating table
				while (petsIter.hasNext())
				{
					// Get current pet from iterator
					petVec.add(petsIter.next());
					// Get pet's details
					petName = petVec.get(index).getName();
					petTypeStr = petVec.get(index).getPet_type().getType_name();
					shortDescStr = petVec.get(index).getShort_desc();
					deliveredByStr = petVec.get(index).getDeliver_user().getUsername(); // TODO: check use of stringbuffer
					userID = Integer.toString(petVec.get(index).getDeliver_user().getId());
					petID = Integer.toString(petVec.get(index).getId());
					
					// Insert current row data into table
					String [] data = {petName, petTypeStr, shortDescStr, deliveredByStr, userID, petID} ;
					try
					{
						tableModel.insertRow(index, data);
						index++;
					}
					catch (ArrayIndexOutOfBoundsException ex)
					{
						throw new ClientRuntimeException(ex.getMessage(), ex);
					}
				}				
			}
			catch (PrivilidgesException ex)
			{
				JOptionPane.showMessageDialog(null, "Insufficient privileges to preform operation",
						"Error", JOptionPane.ERROR_MESSAGE);
				return;
			}
			catch(Exception ex)
			{
				throw new ClientRuntimeException(ex.getMessage(), ex);
			}
		}
	}
	
	protected class getPetDetailsButtonHandler implements ActionListener {
		public void actionPerformed (ActionEvent e) 
		{
			tableRowIndex = petsTable.getSelectedRow();
			if (tableRowIndex != -1)
			{
			SwingUtilities.invokeLater(new Runnable()
			{
	            public void run()
	            {
	            	
	            	// Displaying the pet's details frame
	            	petDetailsFrame.displayPetDetailsFrame(petVec.get(tableRowIndex));
	            }
	        });			
			}
		}
	}

	protected class manageUsersButtonHandler implements ActionListener {
		public void actionPerformed (ActionEvent e) 
		{
			SwingUtilities.invokeLater(new Runnable()
			{
	            public void run()
	            {
	            	// Displaying add users frame
	            	manageUsersFrame = new ManageUsersFrame(clientframe);	            }
				});
		}
	}
	
	protected class managePetTypeButtonHandler implements ActionListener {
		public void actionPerformed (ActionEvent e) 
		{
			SwingUtilities.invokeLater(new Runnable()
			{
	            public void run()
	            {
	            	// Displaying add pet types frame
	            	managePetTypeFrame = new ManagePetTypeFrame(clientframe);
	            }
			});
		}
	}
	
	protected void initPetTypeCombo ()
	{
		/** This Class retrieve pets type and insert pet types' name into
		 * ComboBox.
		 * We insert each pet type into pet type vector in order to get the right
		 * Pet_type object when a pet type's name is selected in ComboBox */
		
		int index;
		int oldSelection;
		
		oldSelection = petTypeComboBox.getSelectedIndex();
		
		try
		{
			// Get pets types iterator from the client parent frame
			petsTypeIter = currClient.session.getAllPetTypes();
			petTypeVec = new Vector<Pet_type>();
			index = 0;
			
			// Clear ComboBox old values
			petTypeComboBox.removeAllItems();
			
			while (petsTypeIter.hasNext())
			{
				// Insert pet type into vector
				petTypeVec.add(petsTypeIter.next());
				
				// Initialize ComboBox with the pet types at the same index as in the Vector
				petTypeComboBox.insertItemAt((petTypeVec.get(index)).getType_name(), index);
				index++;				
			}
			// Check that pets list is not empty
			if (petTypeVec.size() > 0)
			{
				// Initialize CoboBox selection
				if (oldSelection == -1)
				{
					// If the ComboBox has not been used yet, set the selected item as first item
					petTypeComboBox.setSelectedIndex(0);
				}
				else
				{
					// If the ComboBox has not been used already, set the selected item as last selected item
					petTypeComboBox.setSelectedIndex(oldSelection);
				}
				
			}
			else
			{
				petTypeComboBox.setSelectedIndex(-1);
			}
			if (petTypeComboBox.getSelectedItem() == null || petTypeComboBox.getSelectedIndex() == -1)
			{
				// If the PetType table is empty then return
				JOptionPane.showMessageDialog(null, "Ask your administrator to add pet types to the repository",
						"No pet type found in repository", JOptionPane.WARNING_MESSAGE);
				
				// Disable the ability to retreive pets by type
				getPetsListByTypeButton.setEnabled(false);		
			}
			else
			{
				getPetsListByTypeButton.setEnabled(true);		
			}
		}
		catch (PrivilidgesException ex)
		{
			JOptionPane.showMessageDialog(null, "Insufficient privileges to preform operation",
					"Error", JOptionPane.ERROR_MESSAGE);
			
			throw new ClientRuntimeException(ex.getMessage(), ex);
		}
		catch(Exception ex)
		{
			throw new ClientRuntimeException(ex.getMessage(), ex);
		}	
		System.out.println("Debug - left pane size is - Hieght: " + leftPane.getHeight() + " Width " + leftPane.getWidth());

	}
}
